local xingzuo = fk.CreateSkill {

  name = "joy__xingzuo",

  tags = {  },

}



xingzuo:addEffect(fk.EventPhaseStart, {
  name = "joy__xingzuo",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(xingzuo.name) and player.phase == Player.Play
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getNCards(3, "bottom")
    cards = table.reverse(cards)
    --FIXME:从牌堆底获取牌是逆序的……
    local handcards = player:getCardIds(Player.Hand)
    local cardmap = room:askForArrangeCards(player, xingzuo.name,
    {cards, handcards, "Bottom", "$Hand"}, "#xingzuo-invoke")
    U.swapCardsWithPile(player, cardmap[1], cardmap[2], xingzuo.name, "Bottom")
  end,
})

xingzuo:addEffect(fk.EventPhaseStart, {
  name = "#joy__xingzuo_delay",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and not player.dead and player.phase == Player.Finish and
    player:usedSkillTimes(xingzuo.name, Player.HistoryTurn) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p)
      return not p:isKongcheng() end), Util.IdMapper)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#joy__xingzuo-choose", xingzuo.name, true)
    if #to > 0 then
      event:setCostData(self, to[1])
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(xingzuo.name)
    local to = room:getPlayerById(event:getCostData(self))
    local cards = to:getCardIds(Player.Hand)
    local n = #cards
    room:moveCards({
      from = to.id,
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonExchange,
      proposer = player.id,
      skillName = xingzuo.name,
      moveVisible = false,
    })
    if not to.dead then
      room:moveCardTo(room:getNCards(3, "bottom"), Card.PlayerHand, to, fk.ReasonExchange, xingzuo.name, nil, false, player.id)
    end
    cards = table.filter(cards, function (id)
      return room:getCardArea(id) == Card.Processing
    end)
    if #cards > 0 then
      cards = table.random(cards, #cards)
      room:moveCards({
        ids = cards,
        fromArea = Card.Processing,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonExchange,
        skillName = xingzuo.name,
        moveVisible = false,
        drawPilePosition = -1,
      })
    end
  end,
})

return xingzuo